// import { Login, logout, getInfo } from '@/api/admin/admin'
import { Login, loginOut, getInfo } from '@/api/adminuser'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import router from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo:null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER: (state, list) => {
    state.userInfo = list
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    console.log("=========login==========")
    const { username, password,isLogin } = userInfo
    console.log(userInfo)
    return new Promise((resolve, reject) => {
      Login({ name: username.trim(), pwd: password ,isLogin:isLogin}).then(response => {
        console.log(response.data)
        const data  = response.data
        console.log(data.remember_token)
        let str = JSON.stringify(data.menu)
        localStorage.setItem('cr3', str)
        commit('SET_USER', data)
        commit('SET_TOKEN', data.remember_token)
        setToken(data.remember_token)
        commit('SET_NAME', data.username)
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
        console.log(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    console.log("+++++++++++");
    console.log(commit);
    console.log(state);
    return new Promise((resolve, reject) => {
      getInfo({token:state.token}).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        commit('SET_USER', data)
        const { username, name } = data

        commit('SET_NAME', username)
        commit('SET_AVATAR', name)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      loginOut({token:state.token}).then(() => {
        removeToken() // must remove  token  first
        localStorage.removeItem('cr3')
        resetRouter()

        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

